#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""get ip_list of equipments
@author : liujin
@license : Copyright@haohandata
@version : 1.0
@todo : created in 2016-4-26
"""
# 此脚本执行需要指定具体表名，包括equipment、server、switch、tma等

import sys
import os
import subprocess
from configparser import ConfigParser
import tools

config_file = os.getenv("INSPECTOR_HOME") + "/conf/install.conf"

equipment_type_map = {
    "server": 1,
    "TMA": 2,
    "Optiswap": 3,
    "dispatch_platform": 4,
    "switch": 5,
    "firewall": 6,
}


def get_inspector_home():
    inspector_home = os.getenv("INSPECTOR_HOME")

    command = "cd %s" % inspector_home
    result = subprocess.run(
        command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    status = result.returncode
    output = result.stdout.decode("utf-8")
    if status != 0:
        print("INSPECTOR_HOME的环境变量未配置或配置路径%s不存在" % inspector_home)
        sys.exit(1)
    return inspector_home


def get_ip_list(equipment_type):
    serverIp = tools.get_host_ip()
    try:
        if equipment_type == "all":
            rows = tools.get_sql_select_data(
                "select ip from resource.deployed_equipment a \
            left join data.equipment b on a.ip=b.manage_ip left join resource.equipment_model c \
            on b.model_id=c.id left join resource.equipment_type d on c.type_id=d.id where a.server_ip='%s' \
            and (b.engineering_status_id=1 or engineering_status_id=3)"
                % serverIp
            )
        else:
            rows = tools.get_sql_select_data(
                "select ip from resource.deployed_equipment a \
            left join data.equipment b on a.ip=b.manage_ip left join resource.equipment_model c \
            on b.model_id=c.id left join resource.equipment_type d on c.type_id=d.id where d.id=%s and a.server_ip='%s' \
            and (b.engineering_status_id=1 or engineering_status_id=3)"
                % (equipment_type_map[equipment_type], serverIp)
            )
        # 新增HDT探针设备分流子板的采集
        append_rows = []
        if equipment_type == "dispatch_platform":
            append_rows = tools.get_sql_select_data(
                "select ip from resource.deployed_equipment a \
            left join data.equipment b on a.ip=b.manage_ip left join resource.equipment_model c \
            on b.model_id=c.id left join resource.equipment_type d on c.type_id=d.id where d.id=%s and a.server_ip='%s' \
            and (b.engineering_status_id=1 or engineering_status_id=3)"
                % (equipment_type_map["TMA"], serverIp)
            )
    except BaseException as e:
        sys.exit(1)
    ip_list = []
    for row in rows:
        ip_list.append(row[0])
    tma_type_map = tools.get_tma_type_from_db()
    for row in append_rows:
        ip = row[0]
        if tma_type_map.has_key(ip):
            dev_type = tma_type_map[ip]
            if dev_type == "HDT5000":
                ip_list.append(ip + ":1161")
    return ip_list


def get_webmaster_ip_list():
    serverIp = tools.get_host_ip()
    try:
        rows = tools.get_sql_select_data(
            "select b.web_master_ip from resource.deployed_equipment a \
            left join data.equipment b on a.ip=b.manage_ip left join resource.equipment_model c \
            on b.model_id=c.id left join resource.equipment_type d on c.type_id=d.id where a.server_ip='%s'"
            % serverIp
        )
    except BaseException as e:
        sys.exit(1)
    ip_list = []
    for row in rows:
        ip_list.append(row[0])
    return ip_list


def get_ip_list_by_file(type1):
    inspector_home = get_inspector_home()
    ip_list_file = inspector_home + "/conf/ipList.conf"
    cp = ConfigParser.ConfigParser()
    cp.read(ip_list_file)
    opts = []
    ip_list = []
    if type1 == "all":
        # 去掉TMA
        eqlist = ["server", "equipment", "switch", "dispatch_platform"]
        for table in eqlist:
            opts = cp.get(table, "ip")
            ip_list.extend(opts.split(","))
    else:
        opts = cp.get(type1, "ip")
        ip_list = opts.split(",")
    while "" in ip_list:
        ip_list.remove("")
    ip_list = map(str.strip, ip_list)
    return ip_list


def get_ip_list_by_software(software_type):
    """
    通过查询进程管理表获取该软件部署的服务器列表[UASG/UAS/DISPATCHER/RDSG/IMPORTER]
    """
    server_ip = tools.get_host_ip()
    try:
        rows = tools.get_sql_select_data(
            "select a.server_ip from resource.server_software a left join \
            resource.software_manage b on a.software_manage_id=b.id left join resource.deployed_equipment c \
            on a.server_ip=c.ip where b.software_name='%s' and c.server_ip='%s' and a.check_flag is true"
            % (software_type, server_ip)
        )
    except BaseException as e:
        sys.exit(1)
    ip_list = []
    for row in rows:
        ip_list.append(row[0])
    return ip_list


if __name__ == "__main__":
    ip_list = get_ip_list_by_file(sys.argv[1])
    print(ip_list)
